package com.example.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.json.JSONObject;
import com.example.channel.BootNettyChannel;
import com.example.channel.BootNettyChannelCache;
import com.example.controller.vo.BaseResVO;
import com.example.service.ItrafficFlowService;
import io.netty.buffer.Unpooled;
import io.swagger.annotations.*;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @ClassName: DemoController
 * @Author : 13736
 * @Date :2023/7/24  21:39
 * @Description: TODO
 * @Version :1.0
 */
@Api(tags = "TCP服务端调试接口",value = "TCP server debugging interface")
@RestController
public class BootNettyController {

    @Resource
    private ItrafficFlowService itrafficFlowService;

    @GetMapping(value = {"", "/"})
    public String index() {
        return "netty springBoot tcp demo";
    }

    @ApiOperation(value = "获取所有客户端")
    @GetMapping("/clientList")
    @ResponseBody
    public List<Map<String,String>> clientList() {
        List<Map<String,String>> list = new ArrayList<>();
        for (Map.Entry<String, BootNettyChannel> entry : BootNettyChannelCache.channelMapCache.entrySet()) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("code", entry.getKey());
            //map.put("code", entry.getValue().getCode());
            map.put("report_last_data", entry.getValue().getReport_last_data());
            list.add(map);
        }
        return list;
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "xmlStr", value = "XML", dataType = "String", paramType = "body")
    })
    @ApiOperation(value = "向所有客户端发送数据")
    @PostMapping(value = "/downDataToAllClient",consumes = MediaType.TEXT_XML_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
    public BaseResVO downDataToAllClient(@RequestBody String xmlStr) {
        for (Map.Entry<String, BootNettyChannel> entry : BootNettyChannelCache.channelMapCache.entrySet()) {
            BootNettyChannel bootNettyChannel = entry.getValue();
            if(bootNettyChannel != null && bootNettyChannel.getChannel().isOpen()){
                bootNettyChannel.getChannel().writeAndFlush(Unpooled.buffer().writeBytes(xmlStr.toString().getBytes()));
                // netty的编码已经指定，因此可以不需要再次确认编码
                // bootNettyChannel.getChannel().writeAndFlush(Unpooled.buffer().writeBytes(content.getBytes(CharsetUtil.UTF_8)));
            }
        }
        System.out.println(xmlStr);
        Date date = DateUtil.date();
        String nowStr = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss.SSS");
        String data = itrafficFlowService.getXmlStr();
        BaseResVO baseResVO = BaseResVO.builder()
                .receiveMsg(xmlStr.toString())
                .responseMsg(data)
                .receiveTime(nowStr)
                .build();
        return baseResVO;
    }

    @PostMapping("/downDataToClient")
    public String downDataToClient(@RequestParam(name="code", required = true) String code, @RequestParam(name="content", required = true) String content) {
        BootNettyChannel bootNettyChannel = BootNettyChannelCache.get(code);
        if(bootNettyChannel != null && bootNettyChannel.getChannel().isOpen()){
            bootNettyChannel.getChannel().writeAndFlush(Unpooled.buffer().writeBytes(content.getBytes()));
            // netty的编码已经指定，因此可以不需要再次确认编码
            // bootNettyChannel.getChannel().writeAndFlush(Unpooled.buffer().writeBytes(content.getBytes(CharsetUtil.UTF_8)));
            return "success";
        }
        return "fail";
    }
}
